package com.yinshan.voiceplay;

import android.content.Context;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;

import com.coremedia.iso.boxes.Container;
import com.googlecode.mp4parser.authoring.Movie;
import com.googlecode.mp4parser.authoring.Track;
import com.googlecode.mp4parser.authoring.builder.DefaultMp4Builder;
import com.googlecode.mp4parser.authoring.container.mp4.MovieCreator;
import com.googlecode.mp4parser.authoring.tracks.AppendTrack;
import com.yinshan.voiceplay.utils.MoneyUtils;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author limh
 * @function
 * @date 2021/3/25 17:41
 */
public class VoicePlay {
    private static String TAG = "VoicePlay";

    private final List<String> voices = new ArrayList<>();
    private ExecutorService threadPool = null;
    private static VoicePlay instance;
    private Context context;

    public VoicePlay(Context context) {
        this.context = context;
        threadPool = Executors.newCachedThreadPool();
    }

    public static VoicePlay getInstance(Context context) {
        if (null == instance) {
            synchronized (VoicePlay.class) {
                if (null == instance) {
                    instance = new VoicePlay(context);
                }
            }
        }
        return instance;
    }

    public VoicePlay addVoice(String voiceString) {
        Log.d(TAG, "语音内容:" + voiceString);
        voices.clear();
        //‘收款成功’语音索引
        voices.add(context.getResources().getResourceName(R.raw.tts_success));
        String money = MoneyUtils.getMoney(voiceString);
        if (TextUtils.isEmpty(money)) {
            return this;
        }
        //金额转换为语音索引
        if (money.contains(".")) {
            String[] tmp = money.split("\\.");
            voices.addAll(MoneyUtils.readIntPart(context, tmp[0]));
            if (!MoneyUtils.readDecimalPart(tmp[1]).isEmpty()) {
                voices.add(context.getResources().getResourceName(R.raw.tts_dot));
                voices.addAll(MoneyUtils.readDecimalPart(context, tmp[1]));
            }
        } else {
            voices.addAll(MoneyUtils.readIntPart(context, money));
        }
        //‘元’语音索引
        voices.add(context.getResources().getResourceName(R.raw.tts_yuan));
        return this;
    }

    public void mergeVoice() {
        if (voices.isEmpty()) {
            return;
        }
        try {
            Movie[] inMovies = new Movie[voices.size()];
            for (int i = 0; i < voices.size(); i++) {
                Log.w(TAG, "filePaths=" + voices.get(i));
                File f = new File(voices.get(i));
                if (f.exists()) {
                    inMovies[i] = MovieCreator.build(voices.get(i));
                } else {
                    Log.w(TAG, "文件不存在=" + voices.get(i));
                }
            }
            List<Track> audioTracks = new LinkedList<>();
            for (Movie m : inMovies) {
                for (Track t : m.getTracks()) {
                    if (t.getHandler().equals("soun")) {
                        audioTracks.add(t);
                    }
                }
            }
            Movie outMovie = new Movie();
            if (audioTracks.size() > 0) {
                outMovie.addTrack(new AppendTrack(audioTracks.toArray(new Track[audioTracks.size()])));
            }
            Container mp4file = new DefaultMp4Builder().build(outMovie);

            // 将文件输出
            File resultFile = new File(Environment.getExternalStorageDirectory()+"/aaaaa.mp4");
            if (resultFile.exists() && resultFile.isFile()) {
                resultFile.delete();
            }
            FileChannel fc = new RandomAccessFile(resultFile, "rw").getChannel();
            mp4file.writeContainer(fc);
            fc.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
